package handlers

import (
	"article-master/model"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	username := c.PostForm("username")
	likeCount, _ := strconv.Atoi(c.PostForm("likeCount"))
	if title == "" || content == "" || img == "" || username == "" || likeCount == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Article{
		Title:     title,
		Content:   content,
		Img:       img,
		Username:  username,
		LikeCount: likeCount,
	}
	err := model.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func List(c *gin.Context) {
	var articles []model.Article
	title := c.Query("title")
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var total int64
	model.DB.Debug().Model(&model.Article{}).Where("title like ?", "%"+title+"%").Offset(offset).Limit(size).Find(&articles)
	model.DB.Model(&model.Article{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  articles,
		"msg":   "success",
		"total": total,
	})
	return
}
